package cn.zhf.shop.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.zhf.shop.sdk.MyConfig;
import cn.zhf.shop.sdk.WXPay;
import cn.zhf.shop.sdk.WXPayUtil;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class PayUtils {

    private static MyConfig config = new MyConfig();

    private static WXPay wxpay;

    static {
        try {
            wxpay = new WXPay(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
    * @Author: Wls
    * @Date: 15:32 2020/2/5
    * @Description: 向微信支付接口统一下单
    */
    public static String unifiedOrder(String orderId,String orderName,int price) throws Exception{

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", orderName);
        data.put("out_trade_no", orderId);
        data.put("device_info", "WEB");
        data.put("fee_type", "CNY");
        data.put("total_fee", String.valueOf(price));
        data.put("spbill_create_ip", "192.144.184.65");
        data.put("notify_url", "http://www.example.com/order/notify");
        data.put("trade_type", "JSAPI");  // 此处指定为扫码支付
        data.put("product_id", "1");

        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            //组装返回
            Map<String, String> return_data=wxpay.fillRequestData(resp);

            JSONObject jsonObject= JSONUtil.parseObj(return_data);

            String rs=jsonObject.toString();

            System.out.println(rs);

            return rs;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
    * @Author: Wls
    * @Date: 15:32 2020/2/5
    * @Description: 向微信支付接口查询订单支付状态
    */
    public static boolean verifyOrder(String orderId){
        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", orderId);
        try {
            Map<String, String> resp = wxpay.orderQuery(data);
            System.out.println(resp);

            if (resp.get("return_code").equals("SUCCESS")&&resp.get("result_code").equals("SUCCESS")) {
                if (resp.get("trade_state").equals("SUCCESS")) {
                    return true;
                }
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
    * @Author: Wls
    * @Date: 15:33 2020/2/5
    * @Description: 解析微信支付接口传来的的支付信息
    */
    public static String resolveOrderNotify(String xml) throws Exception {
        Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);  // 转换成map

        if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
            return notifyMap.get("out_trade_no");
        }
        else {
            return "ERROR";
        }
    }

    /**
     * 将请求转化为xml
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String parseRequst(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String body = "";
        try {
            ServletInputStream inputStream = request.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); // 设置编码格式“utf-8”否则获取中文为乱码
            while (true) {
                String info = br.readLine();
                if (info == null) {
                    break;
                }
                if (body == null || "".equals(body)) {
                    body = info;
                } else {
                    body += info;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }




}
